package com.ajavaer.framework.core.web.tools;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpTools {

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取节点ip
     *
     * @return
     */
    public static String getHostIpAddr() {
        InetAddress host = null;
        String hostIp = "";
        try {
            host = InetAddress.getLocalHost();// 获取节点ip
            hostIp = host.getHostAddress();
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        }
        return hostIp;
    }
}
